package com.dudu.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;

import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;

import com.dudu.bean.PoolAbilityInfoBean;
import com.dudu.bean.PoolCaseBean;
import com.dudu.bean.UserBean;
import com.dudu.dao.PoolNumberUtilsDao;
import com.dudu.model.PoolCase;
import com.dudu.service.IPoolNumberUtilsService;
import com.dudu.utils.PoolCaseNumberTimeThread;
import com.dudu.utils.ThreadPoolUtils;

import core.CoreDao;

/**
 * 2016年上半年升级后的号码池功能工具类 这个类里面包： 1.含查询账号的配置的号码池的能力的信息 2.号码池号码的使用计数功能
 * 
 * @author weidong
 * 
 */
public class PoolNumberUtilsServiceImpl implements IPoolNumberUtilsService {

    private static final Logger log = core.util.Logger.getLogger(PoolNumberUtilsServiceImpl.class.getSimpleName());

    // 用于数据查询dao
    private PoolNumberUtilsDao poolNumberUtilsDao = new PoolNumberUtilsDao();

    /**
      * 根据应用key和custAccount账号和能力类型，获取相应账号所配置的号码池号码--未经处理
      * @param dao
      * @param appKey
      * @param custAccount
      * @param abilityType
      * @param usePlatNbr
      * @return
      */
    public List<PoolAbilityInfoBean> getPoolNumberInfoList(CoreDao dao, String appKey, String custAccount, String abilityType,String displayNbr, String usePlatNbr,String number_vest) {
	log.info("PoolNumberUtilsServiceImpl.getPoolNumberInfo");
	// 用于后面返回号码的list
	List<PoolAbilityInfoBean> poolNumInfoList = new ArrayList<PoolAbilityInfoBean>();

	try {
	    // 查询账号下配置的号码能力
	    poolNumInfoList = poolNumberUtilsDao.queryPoolNumberInfo(dao, appKey, custAccount, abilityType, displayNbr, usePlatNbr, number_vest);
	    // 判断如果查询的账号下面配置的号码为空，则查询这个账号的父级账号下配置的号码信息
	    if (poolNumInfoList == null || poolNumInfoList.isEmpty()) {
		// 查询账号下配置的号码能力
		poolNumInfoList = poolNumberUtilsDao.queryPoolNumberInfo(dao, appKey, "-1", abilityType, displayNbr, usePlatNbr, number_vest);
	    }
	} catch (Exception e) {
	    e.printStackTrace();
	}
	return poolNumInfoList;
    }

    /**
     * 根据应用key和custAccount账号和能力类型和显号查询配置信息--未经处理
     * 
     * @param dao
     * @param appKey
     * @param custAccount
     * @param abilityType
     * @param displayNbr
     * @param usePlatNbr
     * @return
     */
    public PoolAbilityInfoBean getPoolNumberInfo(CoreDao dao, String appKey, String custAccount, String abilityType, String displayNbr, String usePlatNbr,String number_vest) {
	List<PoolAbilityInfoBean> poolNumInfoList=getPoolNumberInfoList(dao, appKey, custAccount, abilityType, displayNbr, usePlatNbr, number_vest);
	if(null !=poolNumInfoList && poolNumInfoList.size() > 0){
	    return poolNumInfoList.get(0);
	}
	return null;
    }

    	/**
	 * 根据账号标识、能力类型、使用状态、使用次数等信息进行过滤后的
	 * 相应账号所配置的号码池号码
	 * @param dao
	 * @param appKey      应用KEY
	 * @param custAccount cust_account
	 * @param abilityType 能力类型
	 * @param usePlatNbr 强制使用平台号码(值为1时，强制使用平台号码发起)
	 * @param number_vest 地区
	 * @return
	 */
    public PoolAbilityInfoBean getPoolNumberInfoFilter(CoreDao dao, String appKey, String custAccount, String abilityType, String usePlatNbr,String number_vest) {
	log.info("PoolNumberUtilsServiceImpl.getPoolNumberInfoFilter");

	PoolAbilityInfoBean resultPoolAbilityInfo = null;

	// 首先根据账号信息和相应的能力，查询配置的号码CoreDao dao, String appKey, String custAccount, String abilityType, String displayNbr, String usePlatNbr,String number_vest
	List<PoolAbilityInfoBean> listPool = getPoolNumberInfoList(dao, appKey, custAccount, abilityType,null, usePlatNbr,number_vest);
	// 获取当前时间日期
	SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
	Date now = new Date();
	// 获取查询的日期
	String data_time = format.format(now);
	// 查询账号下各个号码的使用情况
	try {
	    // 用于记录使用的号码
	    PoolAbilityInfoBean tmpPoolAbilityInfoUse = null;
	    List<PoolCaseBean> listCase = poolNumberUtilsDao.queryPoolCaseByAcc(dao, appKey, custAccount, abilityType, data_time);
	    // 先判断有哪个号码没有使用，若没有使用，则优先使用这几个号码
	    for (int i = 0; i < listPool.size(); i++) {
		// 获取配置的号码
		PoolAbilityInfoBean tmpPoolAbilityInfo = listPool.get(i);
		resultPoolAbilityInfo = tmpPoolAbilityInfo;
		// 循环查询使用的号码
		for (int j = 0; j < listCase.size(); j++) {
		    // 获取号码使用的详细信息
		    PoolCaseBean tmpPoolCase = listCase.get(j);
		    // 判断两个号码是否相同
		    if (tmpPoolCase.getPool_ability_id().equals(tmpPoolAbilityInfo.getId() + "")) {
			// 获取使用最少的号码
			if (j == 0) {
			    tmpPoolAbilityInfoUse = tmpPoolAbilityInfo;
			}
			resultPoolAbilityInfo = null;
			break;
		    }
		}
		// 判断某个号码没有使用，则使用这个号码
		if (resultPoolAbilityInfo != null) {
		    break;
		}
	    }
	    // 判断某个号码没有使用，则使用这个号码，如果都使用过了，则选择使用最少的号码
	    if (resultPoolAbilityInfo == null) {
		// 选择第一个号码（第一个号码为使用量最少的号码）
		resultPoolAbilityInfo = tmpPoolAbilityInfoUse;
		if (listCase.size() > 0) {
		    // 获取号码使用的详细信息
		    PoolCaseBean tmpPoolCase = listCase.get(0);
		    // poolNumberUtilsDao.updatePoolCaseNumTime(dao,
		    // tmpPoolCase.getId()+"");
		    // 开启线程，更新计数
		    ExecutorService executorService = ThreadPoolUtils.getThreadPoolUtils().getExecutorService();
		    executorService.execute(new PoolCaseNumberTimeThread(dao, tmpPoolCase.getId() + "", poolNumberUtilsDao));
		}

	    } else {
		// 如果判断这个号码的使用次数为0，则在号码计数表中增加一条号码次数
		// 创建新的记录
		PoolCaseBean poolCase = new PoolCaseBean();
		// 向实体类中插入数据
		poolCase.setData_time(data_time);
		poolCase.setPool_ability_id(resultPoolAbilityInfo.getId() + "");
		poolCase.setApp_key(appKey);
		poolCase.setCust_account(custAccount);

		poolCase.setComment_info("");
		// 实体类类型转换
		PoolCase poolCaseModel = new PoolCase();
		BeanUtils.copyProperties(poolCase, poolCaseModel);
		// 插入一条新的记录
		poolNumberUtilsDao.insertPoolCase(dao, poolCaseModel);
	    }
	} catch (Exception e) {
	    e.printStackTrace();
	}
	return resultPoolAbilityInfo;
    }

    /**
     * 根据应用key和custAccount账号，记录号码使用次数
     * 
     * @param dao
     * @param appKey
     * @param custAccount
     * @param poolAbilityId
     * @param user
     * @return
     */
    @Override
    public int recordNumTime(CoreDao dao, String appKey, String custAccount, String poolAbilityId, UserBean user) {
	log.info("PoolNumberUtilsServiceImpl.recordNumTime");
	// 用于返回当前使用的次数
	int resultCount = 0;
	// 获取当前时间日期
	SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
	Date now = new Date();
	// 获取查询的日期
	String data_time = format.format(now);

	try {
	    // 先查询当前数据库里是否有数据
	    PoolCase poolCasetmp = poolNumberUtilsDao.queryNumTimeByAcc(dao, appKey, custAccount, poolAbilityId, data_time);
	    if (poolCasetmp == null) {
		// 创建新的记录
		PoolCaseBean poolCase = new PoolCaseBean();
		// 向实体类中插入数据
		poolCase.setData_time(data_time);
		poolCase.setPool_ability_id(poolAbilityId);
		poolCase.setApp_key(appKey);
		poolCase.setCust_account(custAccount);

		poolCase.setComment_info("");

		// 实体类类型转换
		PoolCase poolCaseModel = new PoolCase();
		BeanUtils.copyProperties(poolCase, poolCaseModel);

		// 插入一条新的记录
		int resultPC = poolNumberUtilsDao.insertPoolCase(dao, poolCaseModel);
		// 判断数据插入是否正确
		if (resultPC != 0) {
		    log.error("插入使用数量数据不正确");
		}
		// 设置返回的数量
		resultCount = 1;
	    } else {
		// 如果已经找到相应数据，则做数据+1
		int resultPC = poolNumberUtilsDao.updatePoolCaseNumTime(dao, poolCasetmp.getId() + "");
		// 判断数据更新是否正确
		if (resultPC != 0) {
		    log.error("更新使用数量数据不正确");
		}
		// 设置返回的数量
		resultCount = Integer.parseInt(poolCasetmp.getNum_time()) + 1;
	    }
	} catch (Exception e) {
	    e.printStackTrace();
	    log.error(e);
	}
	return resultCount;
    }

    /**
     * 根据应用key和custAccount账号和号码能力id查询使用次数
     * 
     * @param dao
     * @param appKey
     * @param custAccount
     * @param poolAbilityId
     * @return
     */
    @Override
    public int queryNumTime(CoreDao dao, String appKey, String custAccount, String poolAbilityId) {
	log.info("PoolNumberUtilsServiceImpl.queryNumTime");
	// 用于返回当前使用的次数
	int resultCount = 0;
	// 获取当前时间日期
	SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
	Date now = new Date();
	// 获取查询的日期
	String data_time = format.format(now);
	try {
	    // 先查询当前数据库里是否有数据
	    PoolCase poolCasetmp = poolNumberUtilsDao.queryNumTimeByAcc(dao, appKey, custAccount, poolAbilityId, data_time);
	    if (poolCasetmp != null) {
		// 如果查询的数据不为空，则获取使用次数
		resultCount = Integer.parseInt(poolCasetmp.getNum_time());
	    }
	} catch (Exception e) {
	    e.printStackTrace();
	    log.error(e);
	}
	return resultCount;
    }

    /**
     * 根据应用key、custAccount账号、日期和号码能力id查询使用次数
     * 
     * @param dao
     * @param appKey
     * @param custAccount
     * @param poolAbilityId
     * @param dateTime
     * @return
     */
    @Override
    public List<PoolCaseBean> queryNumTimeByDate(CoreDao dao, String appKey, String custAccount, String poolAbilityId, String dateTime) {
	log.info("PoolNumberUtilsServiceImpl.queryNumTimeByDate");
	// 用于返回当前使用的次数
	List<PoolCaseBean> resultBean = new ArrayList<PoolCaseBean>();
	;
	try {

	    // 先查询当前数据库里是否有数据
	    List<PoolCase> poolCasetmp = poolNumberUtilsDao.queryNumTimeByAccs(dao, appKey, custAccount, poolAbilityId, dateTime);
	    String[] poolIds = poolAbilityId.split(",");
	    for (String poolid : poolIds) {
		boolean flag = false;
		if (poolCasetmp != null) {
		    for (int i = 0; i < poolCasetmp.size(); i++) {
			PoolCase poolCasetmpBean = poolCasetmp.get(i);
			if (poolid.equals(poolCasetmpBean.getPool_ability_id())) {
			    flag = true;
			    // 获取值
			    PoolCaseBean poolCaseBean = new PoolCaseBean();
			    // 类型转换
			    BeanUtils.copyProperties(poolCasetmpBean, poolCaseBean);
			    // 将结果插入list
			    resultBean.add(poolCaseBean);
			}
		    }
		}
		if (!flag) {
		    PoolCaseBean poolCaseBean = new PoolCaseBean();
		    poolCaseBean.setPool_ability_id(poolid);
		    poolCaseBean.setNum_time("0");
		    // 将结果插入list
		    resultBean.add(poolCaseBean);
		}
	    }

	} catch (Exception e) {
	    e.printStackTrace();
	    log.error(e);
	}
	return resultBean;
    }
}
